package my.diplom.dao.impl;

import my.diplom.dao.IMessageDAO;
import my.diplom.entity.Message;
import my.diplom.entity.User;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 14.07.2009
 * Time: 16:00:17
 * To change this template use File | Settings | File Templates.
 */
public class MessageDAOImpl implements IMessageDAO {

     private static final Logger log = Logger.getLogger(MessageDAOImpl.class);

    private HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public void create(Message message) {
        log.debug("create message");
        template.save(message);
    }

    public void update(Message message) {
        log.debug("update message");
        template.saveOrUpdate(message);
    }

    public Message getById(Long messageId) {
        log.debug("get message by id = " + messageId);
        return (Message) template.get(Message.class, messageId);
    }

    public List<Message> getAll() {
        log.debug("get All messages");
        //noinspection JpaQlInspection
        return template.find("from Message order by date desc");
    }

    public void delete(Message message) {
        log.debug("delete message");
        template.delete(message);
    }

    @Override
    public List<Message> getReceivedByUser(User user) {
       return template.find("from Message m where m.toUser = ?", user);
    }

    @Override
    public List<Message> getSentByUser(User user) {
        return  template.find("from Message m where m.fromUser = ?", user);
    }
}
